﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Tar;
using System.IO;

namespace Super64
{
    public sealed class Tarball
    {
        private TarArchive m_TarArch;
        private List<TarEntry> m_Entries;

        public Tarball(Stream inStream)
        {
            m_TarArch = TarArchive.CreateInputTarArchive(inStream);
            m_TarArch.ProgressMessageEvent += new ProgressMessageHandler(m_TarArch_ProgressMessageEvent);
            m_Entries = new List<TarEntry>();
        }

        void m_TarArch_ProgressMessageEvent(TarArchive archive, TarEntry entry, string message)
        {
            m_Entries.Add(entry);
        }

        public void ListEntries()
        {
            m_TarArch.ListContents();
        }

        public List<TarEntry> Entries
        {
            get { return m_Entries; }
        }

        public Stream ExtractFile(string fname)
        {
            foreach (TarEntry e in m_Entries)
            {
                if (e.File == fname)
                {
                    string p = "C:\\tmp\\temps64roms";
                    Directory.CreateDirectory(p);
                    this.m_TarArch.ExtractContents(p);

                    string[] fz = Directory.GetFiles(p, fname, SearchOption.AllDirectories);

                    if (fz.Length > 0)
                    {
                        FileStream fs = new FileStream(fz[0], FileMode.Open, FileAccess.Read, FileShare.Read);
                        MemoryStream mem = new MemoryStream();
                        fs.CopyTo(mem, (int)fs.Length);
                        fs.Close();
                        Directory.Delete(p);
                    }
                }
            }

            return null;
        }
    }
}
